﻿#include "LoginDlg.h"
#include <QDir>
#include <windows.h>
#include"../ufxconfig.h"

extern MainWindow* g_pMainwindow;
extern CLoginDlg*  g_pLoginDlg;
extern CTPInterface* g_CTPInterface;

CLoginDlg::CLoginDlg(QWidget *parent)
	: QDialog(parent)
{
	setFixedSize(640, 450);
	setMinimumSize(QSize(640, 450));
	setMaximumSize(QSize(640, 450));
	QIcon icon;
	icon.addFile(QStringLiteral(":/iconImagePng"), QSize(), QIcon::Normal, QIcon::Off);
	setWindowIcon(icon);
	loginGroup = new QGroupBox(this);
	loginGroup->setObjectName(QStringLiteral("loginGroup"));
	loginGroup->setGeometry(QRect(240, 80, 351, 291));
	QFont font;
	font.setPointSize(10);
	font.setStyleStrategy(QFont::PreferAntialias);
	loginGroup->setFont(font);
	loginGroup->setAutoFillBackground(true);
	labelServerSel = new QLabel(loginGroup);
	labelServerSel->setObjectName(QStringLiteral("labelServerSel"));
	labelServerSel->setGeometry(QRect(70, 120, 71, 16));
	labelUser = new QLabel(loginGroup);
	labelUser->setObjectName(QStringLiteral("labelUser"));
	labelUser->setGeometry(QRect(70, 40, 54, 12));
	labelPassword = new QLabel(loginGroup);
	labelPassword->setObjectName(QStringLiteral("labelPassword"));
	labelPassword->setGeometry(QRect(70, 80, 54, 12));
	editPassword = new QLineEdit(loginGroup);
	editPassword->setObjectName(QStringLiteral("editPassword"));
	editPassword->setGeometry(QRect(180, 80, 151, 20));
	editPassword->setEchoMode(QLineEdit::Password);
	checkSaveFlag = new QCheckBox(loginGroup);
	checkSaveFlag->setObjectName(QStringLiteral("checkSaveFlag"));
	checkSaveFlag->setGeometry(QRect(250, 200, 81, 16));
	btnLogin = new QPushButton(loginGroup);
	btnLogin->setObjectName(QStringLiteral("btnLogin"));
	btnLogin->setGeometry(QRect(50, 240, 75, 23));
	btnCancel = new QPushButton(loginGroup);
	btnCancel->setObjectName(QStringLiteral("btnCancel"));
	btnCancel->setGeometry(QRect(200, 240, 75, 23));
	cmbServerList = new QComboBox(loginGroup);
	cmbServerList->setObjectName(QStringLiteral("cmbServerList"));
	cmbServerList->setGeometry(QRect(180, 120, 151, 22));
	editBrokerId = new QLineEdit(loginGroup);
	editBrokerId->setObjectName(QStringLiteral("editBrokerId"));
	editBrokerId->setGeometry(QRect(180, 160, 151, 20));
	editBrokerId->setEchoMode(QLineEdit::Password);
	labelBrokerId = new QLabel(loginGroup);
	labelBrokerId->setObjectName(QStringLiteral("labelBrokerId"));
	labelBrokerId->setGeometry(QRect(70, 160, 54, 12));
	cmbUsername = new QComboBox(loginGroup);
	cmbUsername->setObjectName(QStringLiteral("cmbUsername"));
	cmbUsername->setGeometry(QRect(180, 40, 151, 22));
	labelStatus = new QLabel(loginGroup);
	labelStatus->setGeometry(QRect(70, 200, 170, 22));//状态显示Label

	//自定义账号输入框
	listWidget = new QListWidget();
	cmbUsername->setModel(listWidget->model());
	cmbUsername->setView(listWidget);
	cmbUsername->setEditable(true);

    setWindowTitle(QStringLiteral("登录"));
    loginGroup->setTitle(QStringLiteral("登录信息"));
    labelServerSel->setText(QStringLiteral("服务器选择"));
    labelUser->setText(QStringLiteral("资金账号"));
    labelPassword->setText(QStringLiteral("交易密码"));
	editPassword->setInputMask(QString());
    checkSaveFlag->setText(QStringLiteral("记住密码"));
    btnLogin->setText(QStringLiteral("登录"));
    btnCancel->setText(QStringLiteral("取消"));
    editBrokerId->setInputMask(QString());
    labelBrokerId->setText(QStringLiteral("BrokerID"));

	//设置背景图片
	QPixmap png = QPixmap();
	png.load(":/loginBkGrd");
	QPalette palette1 = QPalette();
	palette1.setBrush(QPalette::Background, QBrush(png));
	this->setPalette(palette1);
	this->setAutoFillBackground(true);

	connect(btnLogin, &QPushButton::clicked,this, &CLoginDlg::userLogin);
	connect(btnCancel, &QPushButton::clicked,this, &CLoginDlg::cancelLogin);

	connect(this,SIGNAL(SigShowStatusText(QString)),this,SLOT(ShowStatusText(QString)));

    ReadIniFile();
}

CLoginDlg::~CLoginDlg()
{
}

void CLoginDlg::ShowStatusText(QString text){
	labelStatus->setText(text);
}
void CLoginDlg::ReadIniFile(){

    //从配置文件中读取Server信息
    g_CTPInterface->ServerName = UFXConfig::getInstance()->GetString("ServerInfo","ServerName","");
    g_CTPInterface->ServerTradeAddr = UFXConfig::getInstance()->GetString("ServerInfo","ServerTradeAddr","");
    g_CTPInterface->ServerMarketAddr = UFXConfig::getInstance()->GetString("ServerInfo","ServerMarketAddr","");
    cmbServerList->addItem(g_CTPInterface->ServerName);

    //从配置文件读取Account信息
    QString AccountID=UFXConfig::getInstance()->GetString("config","FundAccount","");
    QString	Password=UFXConfig::getInstance()->GetString("config","PassWord","");
    QString	BrokerID=UFXConfig::getInstance()->GetString("config","BrokerID","");

    cmbUsername->setCurrentText(AccountID);
    editPassword->setText(Password);
    editBrokerId->setText(BrokerID);
    //checkSaveFlag->setCheckState(Qt::Checked);
    checkSaveFlag->setEnabled(false);
}

void CLoginDlg::userLogin()
{
	QString errMsg("");
    int nSaveFlag = checkSaveFlag->checkState();
    m_szUsername = cmbUsername->currentText();
    m_szPassword = editPassword->text();
    m_szBrokerId = editBrokerId->text();

    if("" == m_szUsername || "" == m_szPassword){
        QMessageBox::critical(NULL, QString("ERROR"), QStringLiteral("请输入有效账户及密码"));
    }else{
        m_bCTPTraderResponsed = false;
        m_bCTPMarketResponsed = false;
		m_iErrorID   = 1;

        int iTimeCnt = 0;
		QString ServerName = cmbServerList->currentText();
		
        ///登录CTP服务器
        emit SigShowStatusText(QStringLiteral("登录进度:初始化交易服务器…"));
        g_CTPInterface->InitMdObject(m_szUsername,m_szPassword,m_szBrokerId);//初始化行情服务器
        Sleep(1000);
        g_CTPInterface->InitTradeObject(m_szUsername,m_szPassword,m_szBrokerId,ServerName);//初始化交易服务器

        //循环等待CTP服务器反馈的登录响应
        while (!m_bCTPTraderResponsed || !m_bCTPMarketResponsed){
			Sleep(500);
            if (++iTimeCnt == 100){//超过一定时间后显示用户登录超时
                QMessageBox::critical(this, QString("ERROR"), QStringLiteral("用户登录CTP超时!"));
				return;
			}
		}

		if (0 == m_iErrorID ){
            g_pLoginDlg = NULL;
			this->accept();
		}else{
            QMessageBox::critical(this, QString("ERROR"), QString(m_strCTPErrorMsg));
		}
    }
}

//CTP服务器登陆成功后返回信息 调用函数
void CLoginDlg::OnRspUserLoginTrade(CThostFtdcRspInfoField *pRspInfo){
	if(0 != pRspInfo->ErrorID){
        m_bCTPTraderResponsed = true;
        m_bCTPMarketResponsed = true;
		m_iErrorID   = pRspInfo->ErrorID;
		m_strCTPErrorMsg = QStringLiteral("用户登录失败!")+QStringLiteral("\n错误代码=") +
			QString::number(pRspInfo->ErrorID) + QStringLiteral("\n错误信息=") +  QString::fromLocal8Bit(pRspInfo->ErrorMsg);
	}else{
		emit SigShowStatusText(QStringLiteral("登录进度:登录成功,查询合约…"));
	}
}

///登录请求响应
void CLoginDlg::OnRspUserLoginMarket(CThostFtdcRspInfoField *pRspInfo)
{
    m_bCTPMarketResponsed = true;
    if(0 != pRspInfo->ErrorID){
        m_bCTPTraderResponsed = true;
        m_iErrorID   = pRspInfo->ErrorID;
        m_strCTPErrorMsg = QStringLiteral("用户登录失败!")+QStringLiteral("\n错误代码=") +
            QString::number(pRspInfo->ErrorID) + QStringLiteral("\n错误信息=") +  QString::fromLocal8Bit(pRspInfo->ErrorMsg);
    }
}

//查询合约信息完毕后调用函数
void CLoginDlg::OnRspQryInstrument(){
    m_bCTPTraderResponsed = true;
    m_iErrorID = 0;
    emit SigShowStatusText(QStringLiteral("登录进度:查询合约列表完毕"));
}
void CLoginDlg::cancelLogin()
{
	this->close();
}

void CLoginDlg::showAccount(QString sText){
	cmbUsername->setCurrentText(sText);
	cmbUsername->hidePopup();
}
void CLoginDlg::removeAccount(QString sText){
    int iRow = listWidget->currentRow();
    listWidget->takeItem(iRow);
    cmbUsername->hidePopup();
}

void CLoginDlg::displayUser(QString account)
{
	cmbUsername->setEditText(account);
	cmbUsername->hidePopup();
}
void CLoginDlg::removeUser(QString account)
{
	msgBox->setInfo(tr("remove account"), tr("are you sure to remove account?"), QPixmap(":/loginDialog/attention"), false);
	if(msgBox->exec() == QDialog::Accepted)
	{
		int listCount = listWidget->count();
		for(int i=0; i<listCount; i++)
		{
			QListWidgetItem *item = listWidget->item(i);
			AccountItem *accountItem = (AccountItem *)(listWidget->itemWidget(item));
			QString accountNumber = accountItem->getAccountNumber();
			if(account == accountNumber)
			{
				listWidget->takeItem(i);
				delete item;

				break;
			}
		}
	}
	cmbUsername->hidePopup();
}
